'use strict'

var React = require('react-native');
var {msg} = require('iflux-native');
var QMMktActivity = require('./mkt-activity');
var QMPullRefreshListView = require('./pull-refresh-list-view');
var QMSwipeRefreshListView = require('./swipe-refresh-list-view');
var QMBtnContainer = require('./button');
var fetch = require('./fetch');
var QMConst = require('./const');
var GoodsDetails = require('./goods-details');
var SCREEN_WIDTH = require('Dimensions').get('window').width;
//just do nothing.
var noop = () => {};


var {
  View,
  Text,
  Image,
  Platform,
  PixelRatio,
  StyleSheet,
  StatusBarIOS,
} = React;


var RefreshListView = (
  Platform.OS === 'ios' ?
  QMPullRefreshListView :
  QMSwipeRefreshListView
);


/**
 * 货品列表
 */
var GoodsList = React.createClass({
  getDefaultProps() {
    return {
      url: '',
      style: null,
      onDataReceive: noop,
      /*来源，现在就在值为shelf时有特殊操作*/
      source: '',
      //是不是大图模式
      isThumbnailMode: false
    };
  },


  getInitialState() {
    return {
      skuId: '',
      spuId: '',
      markets: [],
      prices: [],
      priceRange: []
    };
  },


  render() {
    return (
      <View style={[styles.list, this.props.listStyle]}>
        <RefreshListView
          ref='refreshListView'
          url={this.props.url}
          style={this.props.style}
          contentContainerStyle={this.props.isThumbnailMode ? styles.thumbList : null}
          customHeader={this.props.customHeader}
          renderRow={this._renderRow}
          onDataReceive={this._hanldDataReceive}
        />
      </View>
    );
  },


  _renderRow(row, _, index) {
    var mode = this.props.isThumbnailMode;
    var name = row['name'];

    return (
      <View
        key={index}
        style={mode ? styles.box : styles.listRow}
        renderToHardwareTextureAndroid={true}>

        {/*缩略图*/}
        <QMBtnContainer  onPress={row.enabled == 0 ? null : this._handleDetail.bind(this, {spuId: row.pid, skuId: row.id})}>
          <View style={mode ? null : styles.imgBorder} >
            {
              row.enabled == 0 ?
                <Image style={mode ? styles.thumbImg : styles.img} source={{uri: row['img']}} >
                  <View style={styles.imgViewMargin} >
                    <View style={styles.imgView} >
                      <Text style={styles.imgViewText}>已失效</Text>
                    </View>
                  </View>
                </Image>
                :
                row.top == 1 ?
                  <Image style={mode ? styles.thumbImg : styles.img} source={{uri: row['img']}} >
                    <View style={styles.imgViewTop} >
                      <Image style={styles.topImg} source={require('img/top.png')} />
                    </View>
                  </Image>
                  :
                <Image style={mode ? styles.thumbImg : styles.img} source={{uri: row['img']}} />
            }
          </View>
        </QMBtnContainer>


        <View style={[styles.detail, mode && {padding: 8}]}>
          {/*商品名称*/}
          <View style={styles.nameView}>
            <Text
              numberOfLines={2}
              style={row.enabled == 0 ? styles.proText_disabled : styles.proText}
              onPress={row.enabled == 0 ? null : this._handleDetail.bind(this, {spuId: row.pid, skuId: row.id})}>
              {
                row.prepay == 1 ?
                <Text style={{color: '#fff'}}>赠1</Text>
                : null
              }
              {name}
            </Text>
            {
              row.prepay == 1 ?
                <Image style={styles.preImg} source={require('img/pre.png')} /> : null
            }
          </View>

          <View style={styles.proCart}>
            <QMMktActivity data={this.state.markets[index]}/>
            <View style={styles.cartRow}>
              {
                row.enabled == 0 ? <View></View> :
                  <Text style={mode ? styles.thumbPriceText : styles.priceText}>
                    ￥{this.state.prices[index] ? this.state.prices[index].toFixed(2) : this.state.priceRange[index]}
                  </Text>
              }

              {
                row.enabled == 0 ?
                  <QMBtnContainer
                    style={mode ? styles.thumbCartImgContainer : styles.cartImgContainer}
                    onPress={this.props.onDeleteShelf.bind(this, row.pid)}>
                    <Image style={styles.delete} source={require('img/delete_blue.png')} />
                  </QMBtnContainer>
                  :
                  <QMBtnContainer
                    style={mode ? styles.thumbCartImgContainer : styles.cartImgContainer}
                    onPress={this._handlePress.bind(this, {spuId: row.pid, skuId: row.id})}>
                    <Image style={styles.cart} source={require('img/cart_green.png')} />
                  </QMBtnContainer>
              }
            </View>
          </View>
        </View>
      </View>
    );
  },


  /**
   * 购物车
   */
  _handlePress(param) {
    if (__DEV__) {
      console.log('press商品的：', param);
    }

    if (Platform.OS === 'ios') {
      //隐藏StatusBar
      StatusBarIOS.setHidden(true);
    }

	  var component = (
		  <GoodsDetails
		  skuId={param.skuId}
		  spuId={param.spuId}
		  source={this.props.source}/>
	  )
	  msg.emit('app:pop-up', {component: component});
  },


  /**
   * 跳转商品详情
   * @param param
   * @private
   */
  _handleDetail(param) {
    if (__DEV__) {
      console.log('press商品的：', param);
    }

    msg.emit('route:goToNext',  {
      skuId: param.skuId,
      spuId: param.spuId,
      source: this.props.source,
      sceneName: 'ProductDetails'
    });
  },


  /**
   * 获取数据后异步加载营销活动和价格
   * @param data
   * @private
   */
  _hanldDataReceive(data) {

    // 根据pageNum判断是否是刷新和下啦
    var resetData = data.pageNum == 0;

    // 默认为spu，为兼容收藏列表
    var getProductFlag = true;
    if (data.otherData) {
      getProductFlag = data.otherData.getProductFlag;
    }

    // 如果是spu列表，只查询区间价格
    if (getProductFlag) {

      var ids = "";
      data.dataList.forEach((v) => {
        ids += v.idStr + ";";
      });

      if (ids != "") {
        var markets = this.state.markets;
        fetch(`${QMConst.HOST}/goods/markets?goodsIds=` + ids)
          .then((res) => {
            markets = resetData ? res : markets.concat(res);
            this.setState({
              markets: markets
            });
          });

        var priceRange = this.state.priceRange;
        fetch(`${QMConst.HOST}/goods/priceRange`, {
          method: 'POST',
          body: JSON.stringify({
            goodsIds: ids
          })
        }).then((res) => {
          priceRange = resetData ? res : priceRange.concat(res);
          this.setState({
            priceRange: priceRange
          });
        });
      }
    }
    // 如果是sku列表，查询价格和营销活动
    else {

      var ids = "";
      data.dataList.forEach((v) => {
        ids += v.id + ",";
      });

      if (ids != "") {
        var markets = this.state.markets;
        fetch(`${QMConst.HOST}/goods/markets?goodsIds=` + ids)
          .then((res) => {
            markets = resetData ? res : markets.concat(res);
            this.setState({
              markets: markets
            });
          });

        var prices = this.state.prices;
        fetch(`${QMConst.HOST}/goods/prices?goodsIds=` + ids)
          .then((res) => {
            prices = resetData ? res : prices.concat(res);
            this.setState({
              prices: prices
            });
          });
      }
    }

    this.props.onDataReceive(data);
  },

	refreshListView() {
		this.refs.refreshListView.refreshListView();
	}

});


var styles = StyleSheet.create({
  list: {
    flex: 1
  },
  box: {
    width: (SCREEN_WIDTH-10)/2 - 10,
    justifyContent: 'center',
    marginTop: 8,
	  marginLeft: 10,
    borderWidth: 1 / PixelRatio.get(),
    borderColor: '#ebebeb',
    backgroundColor: '#FFF'
  },
  thumbImg: {
    height: (SCREEN_WIDTH-30)/2 - 2 / PixelRatio.get(),
  },
  thumbList: {
    flexWrap: 'wrap',
    flexDirection: 'row',
    backgroundColor: '#fff'
  },
  listRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 10,
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#e1e1e1'
  },
  imgBorder: {
    marginRight: 10,
    width: 90 + 2 / PixelRatio.get(),
    height: 90 + 2 / PixelRatio.get(),
    borderColor: '#ebebeb',
    borderWidth: 1 / PixelRatio.get(),
  },
  imgView: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  imgViewMargin: {
    margin: 5,
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  imgViewText: {
    fontSize: 16,
    color: '#FFFFFF'
  },
  img: {
    width: 90,
    height: 90,
  },
  detail: {
    flex: 1
  },
  proText: {
    flex: 1,
    flexWrap: 'wrap',
    fontSize: 14,
    lineHeight: 20,
    height: 40,
    color: '#333',
  },
  proText_disabled: {
    flex: 1,
    flexWrap: 'wrap',
    fontSize: 14,
    lineHeight: 20,
    height: 40,
    color: '#939495',
  },
  proCart: {
    flex: 1,
  },
  cartRow: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: "space-between",
    alignItems: 'center',
    height: 28,
  },
  cartImgContainer: {
    paddingTop: 6,
    paddingRight: 10,
    paddingLeft: 10,
    backgroundColor: 'transparent',
  },
  thumbCartImgContainer: {
    paddingTop: 6,
    paddingLeft: 10,
    backgroundColor: 'transparent',
  },
  priceText: {
    justifyContent: "center",
    marginTop: 6,
    fontSize: 18,
    height: 22,
    color: '#ff8a00'
  },
  thumbPriceText: {
    justifyContent: "center",
    marginTop: 6,
    fontSize: 18,
    height: 22,
    color: '#ff8a00'
  },
  cart: {
    width: 24,
    height: 22,
  },
  delete: {
    width: 20,
    height: 20,
  },
  preImg: {
    position: 'absolute',
    top: 2,
    width: 18,
    height: 18,
  },
  nameView: {
    flex: 1,
  },
  topImg: {
    width: 43,
    height: 43,
  },
  imgViewTop: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0)',
  }
});


module.exports = GoodsList;
